<template>
  <div>
    <FoldModule v-for="moduleItem in filterList" :not-expend="moduleItem.notExpend" :key="moduleItem.title" :title="moduleItem.title">
      <el-form-item
        v-for="(item) in moduleItem.children"
        :label-width="item.labelWidth"
        :key="item.keyword || item.key"
        prop="content">
        <div slot="label" :title="item.name" class="ellipsisTwo input-form-label">{{ item.name }}</div>
        <FilterModule
          v-model="paramsObj[item.model || 'filterModel']"
          :filter-item="item"
          @queryClick="queryClick"
          @handelSelectChange="handelSelectChange" />
      </el-form-item>
    </FoldModule>
  </div>
</template>
<script>
import { getDepartmentAll, getTagAll } from '@/api/config';
import { getOperateoptions } from '@/api/resource';
import { platformList, orderFormList, getAccountBelong } from '@/api/select';
import { getQuestionReply } from '@/api/flyNotice';
// components
import Title from '@/components/Title';
import FoldModule from './foldModule';
import FilterModule from './filterModule';
// utils
import { allRegionData } from '@/utils/areaConfig';
import { resourceSignStatusOptions } from '@/filters/status';
import { paramsAryToStr } from '@/utils/paramsFormat';
import { TAG_MODULES } from '@/utils/const';
import { journalStatusOptions, selectStatusOptions, journalNodeOptions, voiceAnchorOptions, recommendRankOptions } from '@/utils/const/resouce';
import { cooperationOption } from '@/utils/accountCommonData';

export default {
  components: { Title, FoldModule, FilterModule },
  model: {
    prop: 'paramsObj',
    event: 'changeVal'
  },
  props: {
    paramsObj: {
      type: Object,
      default: () => {
        return {
          filterModel: {},
          filterOptions: {}
        };
      }
    },
    // 平台，1:微信 2: 微博 3:小红书 4.抖音 5:更多  6:直播 7:B站
    activeTabs: {
      type: String | Number,
      default: ''
    },
    /**
     * 自定义字段，数据格式如下
     * dynamicKeyList: {
     *  [platformId]: {
     *    '价格信息': [],
     *    '账号信息': [],
     *    '签约信息': [],
     *    '上刊价格': [],
     *    '成本信息': [],
     *    '更多上刊信息': []
     *  }
     * }
     */
    dynamicKeyList: { // 自定义字段
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      deptTreeList: [],
      operateModeList: [],
      orderPlatformOption: [],
      orderFormOption: [],
      tagTreeList: [],
      questionOption: [],
      answerOption: [],
      accountBelongList: [],
      isExpireList: [
        { 'value': '--', 'label': '--' },
        { 'value': 'overTime', 'label': '已过期' },
        { 'value': 'valid', 'label': '有效期内' }
      ],
      fansNumRange: [
        { label: '5万以下', key: '0-50000' },
        { label: '5万-10万', key: '50000-100000' },
        { label: '10万-50万', key: '100000-500000' },
        { label: '50万-100万', key: '500000-1000000' },
        { label: '100万以上', key: '1000000-' }
      ],
      loadMoreSelectCache: {},
      answerFilterItem: {
        model: 'filterModel',
        keyword: 'answerContent',
        name: '反馈记录',
        type: 'loadMoreSelect',
        valueName: 'name',
        directShow: false,
        multiple: true,
        labelName: 'name',
        isImmediatelyQuery: false,
        placeholder: '请选择反馈记录',
        emptyText: this.qusEmptyText,
        searchkeyword: 'content',
        apiUrl: 'admin/question/replay'
      }
    };
  },
  computed: {
    filterList() {
      // activeTabs 1:微信 2:微博 3:小红书 4:抖音 5:更多 6:直播 7:B站
      let ans = [
        { title: '账号信息', children: this.resourceFilter },
        { title: '基础信息', children: this.baseInfoList },
        { title: '运营信息', children: this.operateInfoList },
        { title: '签约信息', children: this.abutmentList },
        { title: '系统信息', children: this.systemList },
        { title: '询单查询', children: this.flyFilter },
        { title: '更多上刊信息', children: this.moreJournalInfoList }
      ];
      if ([3, 4, 7, 2].includes(Number(this.activeTabs)) || this.activeTabs === '') {
        // 小红书、抖音、B站、微博限定
        ans = ans.concat([
          { title: '上刊价格', children: this.journalKey },
          { title: '成本信息', children: this.costFiter }
        ]);
      }
      if (this.dynamicKeyFilter.length) {
        ans.push({
          title: '自定义字段',
          children: this.dynamicKeyFilter
        });
      }
      return ans;
    },
    resourceFilter() {
      return [
        { model: 'filterModel', keyword: 'resourceName', name: '账号', type: 'input' },
        { model: 'filterModel', keyword: 'code', name: '账号ID', type: 'input' },
        { model: 'filterModel', keyword: 'link', name: '链接', type: 'input' },
        { model: 'filterModel', keyword: 'tag', name: '标签', valueName: 'name', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true }
      ];
    },
    // 基础信息
    baseInfoList() {
      return [
        { model: 'filterOptions', keyword: 'fansNum', name: '粉丝量', type: 'inputRadioRange',
          min: 0, range: this.fansNumRange, startPlaceholder: '最低粉丝量', endPlaceholder: '最高粉丝量', max: 999999999
        },
        {
          keyword: 'area', name: '地区', valueName: 'label', model: 'filterModel',
          labelName: 'label', checkStrictly: true, separator: '-',
          childrenVal: 'children', type: 'cascaderSelect', options: allRegionData,
          emitPath: true, filterable: true
        },
        { keyword: 'isExpire', name: '报价有效期', model: 'filterOptions', type: 'select',
          options: this.isExpireList
        },
        { keyword: 'accounts', name: '批量搜索账号', model: 'filterModel',
          type: 'input', inputType: 'textarea',
          lengthLimit: false, placeholder: '可通过粘贴快速填写账号名称，每行代表一个账号名称'
        }
      ];
    },
    // 运营信息
    operateInfoList() {
      return [
        { model: 'filterModel', keyword: 'departmentId', name: '所属经营体', type: 'cascaderSelectWithChild',
          childrenVal: 'children', options: this.deptTreeList },
        // { model: 'filterModel', keyword: 'departmentNames', name: '所属经营体', type: 'input' },
        { model: 'filterOptions', keyword: 'accountBelong', name: '账号归属', type: 'mulSelect',
          options: this.accountBelongList, valueName: 'id', labelName: 'value'
        },
        { model: 'filterModel', keyword: 'operateMode', name: '运营模式', valueName: 'value',
          multiple: true, checkStrictly: false, labelName: 'label',
          childrenVal: 'children', type: 'cascaderSelect', options: this.operateModeList
        },
        { model: 'filterModel', keyword: 'operator', name: '合作运营方', type: 'input', placeholder: '搜索多个用英文逗号“,”隔开' },
        { keyword: 'supplierType', name: '供应商类型', type: 'select', model: 'filterModel',
          options: [{ value: 0, label: '公司' }, { value: 1, label: '个人' }]
        },
        { model: 'filterModel', keyword: 'microTask', name: '挂靠', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        },
        {
          model: 'filterModel', keyword: 'executor', name: '所有人员', type: 'input',
          doubleClick: true, placeholder: '请输入，双击填充当前用户'
        },
        {
          model: 'filterModel', keyword: 'followUsers', name: '跟进人', type: 'input',
          doubleClick: true, placeholder: '请输入，双击填充当前用户'
        },
        {
          model: 'filterModel', keyword: 'status', name: '有效状态', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        },
        { model: 'filterModel', keyword: 'isNewAccount', name: '新号', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        }
      ];
    },
    // 签约信息
    abutmentList() {
      return [
        { model: 'filterModel', keyword: 'signDetailStatus', name: '签约状态', type: 'mulSelect', options: resourceSignStatusOptions, isSearch: true },
        {
          model: 'filterModel', keyword: 'expiredDuration', name: '到期时长', type: 'input',
          placeholder: '请输入数字', inputType: 'number', min: 0
        },
        {
          model: 'filterModel', keyword: 'contractBroker', name: '签单签约经纪', type: 'input',
          doubleClick: true, placeholder: '请输入，双击填充当前用户'
        },
        {
          model: 'filterModel', keyword: 'followContractBroker', name: '现维护经纪人', type: 'input',
          doubleClick: true, placeholder: '请输入，双击填充当前用户'
        },
        { model: 'filterModel', keyword: 'selectionStatus', name: '选号状态', type: 'select',
          options: selectStatusOptions, labelName: 'value', valueName: 'id'
        },
        { model: 'filterModel', keyword: 'journalStatus', name: '上刊状态', type: 'select',
          options: journalStatusOptions, labelName: 'value', valueName: 'id'
        },
        { model: 'filterModel', keyword: 'journalNode', name: '上刊节点', type: 'select',
          options: journalNodeOptions, labelName: 'value', valueName: 'id'
        },
        { model: 'filterModel', keyword: 'cooperationOption', name: '合作方式', type: 'select',
          options: cooperationOption, labelName: 'label', valueName: 'value'
        },
        // { model: 'filterModel', keyword: 'publicationTime', name: '上刊日期', type: 'date', hideLabel: true, format: 'yyyy/MM/dd', dateType: 'date', placeholder: '请选择日期'
        // },
        { model: 'filterModel', keyword: 'publicationMonth', name: '上刊月份', type: 'date', hideLabel: true, format: 'yyyy/MM'
        },
        {
          model: 'filterModel', keyword: 'executeBroker', name: '执行经纪', type: 'input',
          doubleClick: true, placeholder: '请输入，双击填充当前用户'
        },
        {
          model: 'filterModel', keyword: 'expertOperator', name: '达人运营', type: 'input',
          doubleClick: true, placeholder: '请输入，双击填充当前用户'
        },
        { model: 'filterModel', keyword: 'signGroups', name: '签约所属部门', type: 'cascaderSelectWithChild',
          childrenVal: 'children', options: this.deptTreeList
        },
        { model: 'filterModel', keyword: 'signDate', name: '签约有效期', timeType: 'daterange', type: 'rangeDate'
        },
        { model: 'filterModel', keyword: 'signExpireDate', name: '签约截止日期', timeType: 'daterange', type: 'rangeDate'
        },
        { model: 'filterModel', keyword: 'cooperationTime', name: '试合作期', timeType: 'monthrange', type: 'rangeDate', format: 'yyyy/MM', startPlaceholder: '开始月份', endPlaceholder: '结束月份'
        }
      ];
    },
    systemList() {
      return [
        { model: 'filterModel', keyword: 'creator', name: '创建人', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { model: 'filterModel', keyword: 'systemId', name: '系统ID', type: 'input', inputType: 'pureNumber' },
        { model: 'filterModel', keyword: 'regenerator', name: '更新人', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { model: 'filterModel', keyword: 'autoPick', name: '自动采集', type: 'select',
          options: [{ value: 0, label: '未开启' }, { value: 1, label: '已开启' }]
        },
        { model: 'filterModel', keyword: 'orderNum', name: '订单数', type: 'inputRange', startPlaceholder: '最小数量', endPlaceholder: '最大数量', onlyInteger: true, min: 0, max: 999999999 },
        { model: 'filterModel', keyword: 'createTime', name: '创建时间', timeType: 'daterange', type: 'rangeDate'
        }
      ];
    },
    opEmptyText() {
      if (this.paramsObj.filterModel.queryPlatformId) {
        return '无数据';
      }
      return '请先选择询单平台';
    },
    flyFilter() {
      const ans = [
        { model: 'filterModel', keyword: 'brandName', name: '品牌名称', type: 'input', placeholder: '请输入品牌名称' },
        { model: 'filterModel', keyword: 'productName', name: '产品名称', type: 'input', placeholder: '请输入产品名称' },
        { model: 'filterModel', keyword: 'queryPlatformId', name: '询单平台', type: 'select',
          options: this.orderPlatformOption, valueName: 'id', labelName: 'value'
        },
        { model: 'filterModel', keyword: 'cooperationFormId', name: '合作形式',
          type: 'mulSelect', emptyText: this.opEmptyText, options: this.orderFormOption,
          valueName: 'id', labelName: 'value'
        },
        {
          model: 'filterModel', keyword: 'questionId',
          name: '问题',
          type: 'loadMoreSelect',
          valueName: 'id',
          directShow: false,
          multiple: false,
          labelName: 'content',
          placeholder: '请选择问题',
          extendParams: { includeDescription: true },
          searchkeyword: 'content',
          apiUrl: 'admin/question/search'
        },
        this.answerFilterItem,
        { model: 'filterModel', keyword: 'responseStatus', name: '响应状态', type: 'select',
          options: [
            { value: 0, label: '待响应' },
            { value: 1, label: '感兴趣' },
            { value: 2, label: '暂不考虑' }
          ]
        },
        { model: 'filterModel', keyword: 'queryTagName', name: '询单标签', valueName: 'name', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true, placeholder: '请选择询单标签'
        }
      ];
      if (this.paramsObj.filterModel.questionId) {
        this.$set(this.answerFilterItem, 'emptyText', '无数据');
      } else {
        this.$set(this.answerFilterItem, 'defaultParams', []);
        this.$set(this.answerFilterItem, 'emptyText', '请先选择问题');
      }
      return ans;
    },
    moreJournalInfoList() {
      return [
        {
          model: 'filterModel', keyword: 'recommendRank', name: '推荐优先级', type: 'select', placeholder: '请选择',
          options: recommendRankOptions, labelName: 'value', valueName: 'id'
        },
        {
          model: 'filterModel', keyword: 'isFrameOut', name: '露脸', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        },
        {
          model: 'filterModel', keyword: 'isVoiceAnchor', name: '口播', type: 'select', placeholder: '请选择',
          options: voiceAnchorOptions, labelName: 'value', valueName: 'id'
        },
        {
          model: 'filterModel', keyword: 'freeAuth', name: '可全平台免费授权6个月信息流/电商投放以及二次剪辑', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        },
        {
          model: 'filterModel', keyword: 'otherFreePlatform', name: '可免费同步其他平台', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        },
        {
          model: 'filterModel', keyword: 'hasShopPrice', name: '可免费同城探店', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        },
        {
          model: 'filterModel', keyword: 'retentionAllowed', name: '可永久保留内容', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        },
        {
          model: 'filterModel', keyword: 'addBrand', name: '可免费添加品牌标记组件，评论区组件等', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        },
        {
          model: 'filterModel', keyword: 'allowCar', name: '可免费挂车', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        },
        {
          model: 'filterModel', keyword: 'carCommission', name: '对挂车佣金无要求', type: 'select', placeholder: '请选择',
          options: [{ value: 0, label: '否' }, { value: 1, label: '是' }]
        }
      ];
    },
    journalKey() {
      const xhs = [
        {
          model: 'filterOptions', keyword: 'monthReportPrice',
          name: '本月报备价(即本月平台价格)', type: 'inputRange', newOptions: true
        },
        {
          model: 'filterOptions', keyword: 'nextMonthReportPrice',
          name: '次月报备价(即次月平台价格)', type: 'inputRange', newOptions: true
        },
        {
          model: 'filterOptions', keyword: 'monthNotReportPrice',
          name: '本月非报备价', type: 'inputRange', newOptions: true
        },
        {
          model: 'filterOptions', keyword: 'nextMonthNotReportPrice',
          name: '次月非报备价', type: 'inputRange', newOptions: true
        }
      ];
      const other = [{
        model: 'filterOptions', keyword: 'articlesPrice', name: '刊例价格', type: 'inputRange', newOptions: true }
      ];
      const date = [
        { model: 'filterModel', keyword: 'priceUpdateDate', name: '上刊价格更新日期', timeType: 'daterange', type: 'rangeDate' }
      ];
      if (Number(this.activeTabs) === 3) {
        return [...xhs, ...date];
      } else if (this.activeTabs === '') {
        return [...xhs, ...other, ...date];
      }
      return [...other, ...date];
    },
    costFiter() {
      const xhs = [
        {
          model: 'filterOptions', keyword: 'monthReportPriceCost', name: '本月报备价', type: 'costType', newOptions: true
        },
        {
          model: 'filterOptions', keyword: 'nextMonthReportPriceCost', name: '次月报备价', type: 'costType', newOptions: true
        },
        {
          model: 'filterOptions', keyword: 'monthNotReportPriceCost', name: '本月非报备价', type: 'costType', newOptions: true
        },
        {
          model: 'filterOptions', keyword: 'nextMonthNotReportPriceCost', name: '次月非报备价', type: 'costType', newOptions: true
        }
      ];
      const other = [{
        model: 'filterOptions', keyword: 'costPrice', name: '成本价格', type: 'costType', newOptions: true
      }];
      if (Number(this.activeTabs) === 3) {
        return xhs;
      } else if (this.activeTabs === '') {
        return [...xhs, ...other];
      }
      return other;
    },
    dynamicKeyFilter() {
      const ans = [];
      const dynamicKeyList = this.dynamicKeyList;
      Object.keys(dynamicKeyList).forEach(platformId => {
        Object.keys(dynamicKeyList[platformId]).forEach(key => {
          (dynamicKeyList[platformId][key] || []).forEach(i => {
            // inputType 0:输入框 1:下拉
            ans.push({
              model: 'filterOptions',
              isDynamicKey: true,
              modelKey: this.stringToModel(key),
              keyword: i.id,
              name: i.name,
              type: i.inputType === 0 ? 'input' : 'select',
              options: i.options
            });
          });
        });
      });
      return ans;
    }
  },
  watch: {
    'paramsObj.filterModel.queryPlatformId'(list) {
      if (!list || !list.length) {
        this.orderFormOption = [];
      }
    },
    'paramsObj.filterModel.questionId': {
      handler: function(val) {
        if (val) {
          this.answerOption = [];
          this.getQuestionReply();
          this.$set(this.paramsObj['filterModel'], 'answerContent', '');
        }
      }
    }
  },
  created() {
    this.$nextTick(() => {
      this.queryDeptTreeList();
      this.getOperate();
      this.platformList();
      this.getOrderForm();
      this.queryTagTreeList();
      this.accountBelongOptionsList();
    });
  },
  methods: {
    stringToModel(key) {
      const obj = {
        '价格信息': 'priceInfo',
        '账号信息': 'accountInfo',
        '签约信息': 'handoverKey',
        '上刊价格': 'journalKey',
        '成本信息': 'costInfoKey',
        '更多上刊信息': 'moreJournalKey'
      };
      return obj[key] || null;
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    // 账号归属
    async accountBelongOptionsList() {
      try {
        const result = await getAccountBelong();
        if (result && result.data) {
          this.accountBelongList = result.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 获取运营模式的列表
    getOperate() {
      getOperateoptions().then(res => {
        this.operateModeList = res.data;
      });
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取下单形式
    async getOrderForm() {
      const params = { platformId: this.paramsObj.filterModel.queryPlatformId };
      paramsAryToStr(['platformId'], params);
      if (!params.platformId) {
        return;
      }
      try {
        const result = await orderFormList(params.platformId);
        this.orderFormOption = result.data;
        if (this.paramsObj.filterModel.cooperationFormId) {
          const formId = this.orderFormOption.find(i => this.paramsObj.filterModel.cooperationFormId.includes(i.id));
          if (!formId) this.$set(this.paramsObj.filterModel, 'cooperationFormId', '');
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 获取问题的反馈记录
    getQuestionReply(content) {
      const { questionId } = this.paramsObj.filterModel;
      if (!questionId) return;
      if (questionId) {
        const params = {
          questionId
        };
        if (content) params.content = content;
        getQuestionReply(params).then(res => {
          this.answerOption = (res && res.data && res.data.items) || [];
          this.$set(this.answerFilterItem, 'extendParams', { questionId });
          this.$set(this.answerFilterItem, 'defaultParams', this.answerOption);
          this.$nextTick(() => {
            this.$set(this.answerFilterItem, 'multiple', this.questionType === 2);
          });
        }).catch(err => console.error(err));
      }
    },
    // 标签
    queryTagTreeList() {
      const params = { type: TAG_MODULES.RESOURCE };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    handelSelectChange({ item }) {
      if (item.type === 'loadMoreSelect' && !item.multiple) {
        this.loadMoreSelectCache[item.keyword] = JSON.parse(JSON.stringify(item));
      }
      if (item.keyword === 'questionId') {
        this.$set(this.paramsObj.filterModel, 'answerContent', '');
      }
      if (item.keyword === 'queryPlatformId') {
        this.$set(this.paramsObj.filterModel, 'cooperationFormId', '');
        this.getOrderForm();
      }
    },
    queryClick() {
      this.$emit('queryClick');
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__label {
  line-height: 32px !important;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 32px;
  color: #666;
}
::v-deep .el-form-item {
  margin-bottom: 13px;
}
.input-form-label {
  line-height: 1.2;
}
</style>
